package test;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import test.IO.Input;
import test.IO.Output;
import test.Issue.Issue;
import test.config.Config;
import test.workflow.Flow;
import test.workflow.Statuses;


public class Main {

	public static String flowStatus = Statuses.LOGIN_NEEDED;
	public static List<Issue> priorityIssues = new ArrayList<Issue>();
	public static Issue actualIssue;
	static String startPorgressAnchorHREF;

	public static void main(final String[] args) {
		try {
			initConfig();
			
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			Output.log(formatter.format(new Date()));
			Output.log("Reading config file.");			

			if (flowStatus.equals(Statuses.LOGIN_NEEDED)) {
				Output.log("Logging in.");

				Flow.login(Config.getJiraUrl(), Config.getJiraUsername(),
						Config.getJiraPassword());
				flowStatus = Statuses.SEARCH_FOR_PRIORITY_ISSUES;
			}

			if (flowStatus.equals(Statuses.SEARCH_FOR_PRIORITY_ISSUES)) {
				Output.log("Searching for priority issues.");
				priorityIssues = Flow.searchForPriorityIssuesToProcess(Config
						.getJiraIssueFilterURL(), true);

				if (priorityIssues != null && priorityIssues.size() > 0) {
					Output.log("Priority issues:");
					for (Issue issue : priorityIssues) {
						Output.log(issue.toString());
					}
					flowStatus = Statuses.OPEN_ISSUE;
				} else {
					Output.log("No priority issue have found!");
				}
			}

			if (flowStatus.equals(Statuses.OPEN_ISSUE)) {
				actualIssue = priorityIssues.get(0);
				Output.log("Opening issue:");
				Output.log(actualIssue.toString());

				String anchorId = "action_id_41";

				InputStream openIssueInputStream = Flow.openIssue(Config
						.getJiraUrl()
						+ "browse/", actualIssue.getId());

				String filename = Config.getTmpFilePath() + actualIssue.getId()
						+ ".html";
				
				Output.log("Saving issue text to file: "+filename);
				String issueText = Output
						.inputStreamToString(openIssueInputStream);
				Output.toFile(filename, issueText, false);

				startPorgressAnchorHREF = Input.getAnchorHREFByID(
						new ByteArrayInputStream(issueText.getBytes()),
						anchorId);

				String jiraInernalId = Input.paramterFromUrlGetMap(
						startPorgressAnchorHREF, "id");
				actualIssue.setJiraInernalId(jiraInernalId);

				Output.log("In Progress anchor: "
						+ startPorgressAnchorHREF);
				flowStatus = Statuses.START_PROGRESS;
			}

			if (flowStatus.equals(Statuses.START_PROGRESS)) {
				Output.log("Start progress requesting. Response: ");
				
				String startProgressUrl = Config.getJiraUrl()
						+ "secure/CommentAssignIssue.jspa";
				Output.log(Output.inputStreamToString(Flow.startWork(
						startProgressUrl, actualIssue)));
			}
			Output.log("--------------");
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}

	public static void initConfig() throws FileNotFoundException, IOException {

		Properties properties = new Properties();
		properties.load(new FileInputStream("main.properties"));

		Config.setJiraUrl(properties.getProperty("jira_url"));
		Config.setJiraUsername(properties.getProperty("jira_username"));
		Config.setJiraPassword(properties.getProperty("jira_password"));
		Config.setJiraIssueFilterURL(properties
				.getProperty("jira_issue_filter_url"));
		Config.setTmpFilePath(properties.getProperty("tmp_file_path"));
		Config.setProxy(Boolean.parseBoolean(properties.getProperty("proxy")));
		Config.setProxyHost(properties.getProperty("proxy_host"));
		Config.setProxyPort(Integer.parseInt(properties
				.getProperty("proxy_port")));
		Config.setLogToFile(Boolean.parseBoolean(properties.getProperty("log_to_file")));
		Config.setMaxIssuePriorityToProcess(Integer.parseInt(properties.getProperty("max_issue_priority_to_process")));

	}

}
